import { getLat, getLng, getMapType, getMapZoom, getNetModel, setMapZoom } from '@/util/storage'
import { gcj_decrypt, gcj_encrypt } from '@/util/gps'
import mapStyle from '@/util/custom_map_config.json'
import { loadScript } from '@/util/common'

let mapType = getMapType()
const netModel = getNetModel()

// mapType = 'google'

export function initMap() {
  if (netModel === 'local' && mapType === 'baidu') {
    loadScript('./bmap-offline/map3.0_init.js')
    loadScript('./bmap-offline/map3.0.js&callback=initialize')
    loadScript('./bmap-offline/library/TextIconOverlay_min.js')
    loadScript('./bmap-offline/library/MarkerClusterer_min.js')
  } else if (mapType === 'google') {
    loadScript('https://maps.googleapis.com/maps/api/js?key=AIzaSyCdEl9wuiSpNp6_1_VWHJlTMlf2DZz-kjI')
  }
  // else {
  //   loadScript('https://api.map.baidu.com/api?v=2.0&ak=rU8qkC216C0zEXnKTeKYHzubOHFzowRL&callback=initialize')
  //   loadScript('https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js')
  //   loadScript('https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js')
  // }
}

export function changeMap() {
  mapType = getMapType()
}

export function listMapModel(that) {
  return [{
    label: that.$t('point'),
    icon: 'el-icon-s-grid',
    value: 'point'
  }, {
    label: that.$t('area'),
    icon: 'el-icon-menu',
    value: 'area'
  }, {
    label: that.$t('geo'),
    icon: 'el-icon-menu',
    value: 'geo'
  }]
}

export function listMapType(that) {
  return [{
    label: that.$t('baidu'),
    value: 'baidu'
  }, {
    label: that.$t('qq'),
    value: 'qq'
  }, {
    label: that.$t('google'),
    value: 'google'
  }]
}

export function zoom(map, zoom) {
  if (mapType === 'baidu') {
    map.zoomTo(zoom)
  } else if (mapType === 'qq') {
    map.zoomTo(zoom)
  } else if (mapType === 'google') {
    map.setZoom(zoom)
  }
}

export function hideInfoWindow(map, infoWindow) {
  if (!infoWindow) {
    return
  }
  if (mapType === 'baidu') {
    // infoWindow.setMap(null)
    infoWindow.close()
  } else if (mapType === 'qq') {
    infoWindow.close()
  } else if (mapType === 'google') {
    infoWindow.close()
  }
}

export function setCenter(map, lat, lng) {
  if (mapType === 'baidu') {
    const point = new window.BMap.Point(lng, lat)
    map.panTo(point)
  } else if (mapType === 'qq') {
    const latLng = gcj_encrypt(lat, lng)
    const center = new window.qq.maps.LatLng(latLng.lat, latLng.lng)
    map.setCenter(center)
  } else if (mapType === 'google') {
    const center = new window.google.maps.LatLng(lat, lng)
    map.setCenter(center)
  }
}

export function makeInfoWindow(map, lat, lng, content) {
  let infoWindow
  if (mapType === 'baidu') {
    infoWindow = new window.BMap.InfoWindow(content)
    let point
    if (lat && lng) {
      point = new window.BMap.Point(lng, lat)
    } else {
      point = map.getCenter()
    }
    map.openInfoWindow(infoWindow, point)
  } else if (mapType === 'qq') {
    let center
    if (lat && lng) {
      const latLng = gcj_encrypt(lat, lng)
      center = new window.qq.maps.LatLng(latLng.lat, latLng.lng)
    } else {
      center = map.getCenter()
    }
    infoWindow = new window.qq.maps.InfoWindow({
      draggable: true,
      content: content,
      position: center,
      map: map
    })
    infoWindow.open()
  } else if (mapType === 'google') {
    infoWindow = new window.google.maps.InfoWindow({
      content: content
    })
    const center = new window.google.maps.LatLng(lat, lng)
    const marker = new window.google.maps.Marker({
      map,
      position: center
    })
    infoWindow.open({
      anchor: marker,
      map,
      shouldFocus: false
    })
  }
  return infoWindow
}

export function makeMap(dom, lat, lng, zoom = parseInt(getMapZoom())) {
  lat = Number(lat || getLat())
  lng = Number(lng || getLng())
  let map
  if (mapType === 'baidu') {
    map = new window.BMap.Map(dom) // 创建Map实例
    map.centerAndZoom(new window.BMap.Point(lng, lat), zoom)
    map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
    map.setMapStyle({ styleJson: mapStyle })
  } else if (mapType === 'qq') {
    const latLng = gcj_encrypt(lat, lng)
    const center = new window.qq.maps.LatLng(latLng.lat, latLng.lng)
    map = new window.qq.maps.Map(dom, {
      disableDefaultUI: true, // 禁止所有控件
      mapStyleId: 'style1',
      center: center,
      zoom: zoom
    })
  } else if (mapType === 'google') {
    const center = new window.google.maps.LatLng(lat, lng)
    const mapProp = {
      disableDefaultUI: true,
      center: center,
      zoom: zoom,
      mapTypeId: window.google.maps.MapTypeId.ROADMAP
    }
    map = new window.google.maps.Map(dom, mapProp)
    map.setTilt(45)
  }
  map.ztn = {}
  map.ztn.markerList = []
  createdZoomListener(map, (p) => {
    setMapZoom(p.zoom)
  })
  return map
}

// export function getMarkerInfo(marker) {
//   const info = {}
//   if (mapType === 'baidu') {
//     info.lat = marker.point.lat
//     info.lng = marker.point.lng
//   } else if (mapType === 'qq') {
//     info.lat = marker.position.lat
//     info.lng = marker.position.lng
//   }
//   return info
// }
export function createdZoomListener(map, fun) {
  if (mapType === 'baidu') {
    map.addEventListener('zoomend', function() {
      const p = {
        zoom: this.getZoom()
      }
      fun(p)
    })
  } else if (mapType === 'qq') {
    window.qq.maps.event.addListener(
      map,
      'zoom_changed',
      function(e) {
        const p = {
          zoom: e.target.zoom
        }
        fun(p)
      }
    )
  } else if (mapType === 'google') {
    /**
     * 没测试过
     */
    window.google.maps.event.addListener(map, 'zoomend', function(e) {
      const p = {
        zoom: e.target.zoom
      }
      fun(p)
    })
  }
}

export function createdMarket(map, lat, lng, iconUrl) {
  let marker
  if (mapType === 'baidu') {
    const point = new window.BMap.Point(lng, lat)
    let icon
    if (iconUrl) {
      icon = new window.BMap.Icon(iconUrl, new window.BMap.Size(40, 40))
    } else {
      icon = new window.BMap.Icon(`${window.VUE_APP_BASE_API}/file/download/static/iot/uni/map/numsImage/red/marker.png`, new window.BMap.Size(20, 20))
    }
    marker = new window.BMap.Marker(point, { icon: icon }) // 创建标注
  } else if (mapType === 'qq') {
    const latLng = gcj_encrypt(lat, lng)
    const center = new window.qq.maps.LatLng(latLng.lat, latLng.lng)
    marker = new window.qq.maps.Marker({
      position: center,
      map: map
    })
    if (iconUrl) {
      const scaleSize = new window.qq.maps.Size(40, 40)
      const icon = new window.qq.maps.MarkerImage(
        iconUrl,
        null,
        null,
        null,
        scaleSize
      )
      marker.setIcon(icon)
    }
  } else if (mapType === 'google') {
    const center = new window.google.maps.LatLng(lat, lng)
    const param = {
      position: center
    }
    if (iconUrl) {
      param.icon = {
        url: iconUrl
        // size: new window.google.maps.Size(40, 40),
        // The origin for this image is (0, 0).
        // origin: new window.google.maps.Point(20, 20),
        // The anchor for this image is the base of the flagpole at (0, 32).
        // anchor: new window.google.maps.Point(0, 10)
      }
    }
    marker = new window.google.maps.Marker(param)
  }
  marker.ztn = {}
  map.ztn.markerList.push(marker)
  return marker
}

export function makeMarket(map, lat, lng, iconUrl) {
  const marker = createdMarket(map, lat, lng, iconUrl)
  if (mapType === 'baidu') {
    map.addOverlay(marker)
    // map.centerAndZoom(point, 8) // 初始化地图,设置中心点坐标和地图级别
    // map.panTo(point)
  } else if (mapType === 'google') {
    marker.setMap(map)
  }
  return marker
}

export function clearAllMarket(map) {
  if (mapType === 'baidu') {
    map.clearOverlays()
  } else if (mapType === 'qq') {
    map.ztn.markerList.forEach(marker => {
      marker.setMap(null)
    })
  } else if (mapType === 'google') {
    map.ztn.markerList.forEach(marker => {
      marker.setMap(null)
    })
  }
  map.ztn.markerList = []
}

export function clearAndMakeMarket(map, lat, lng) {
  clearAllMarket(map)
  return makeMarket(map, lat, lng)
}

export function addMapClickListener(map, fun) {
  if (mapType === 'baidu') {
    map.addEventListener('click', function(e) {
      const param = {}
      param.latLng = {
        lat: e.point.lat,
        lng: e.point.lng
      }
      fun(param)
    })
  } else if (mapType === 'qq') {
    window.qq.maps.event.addListener(map, 'click', function(e) {
      const latLng = gcj_decrypt(e.latLng.lat, e.latLng.lng)
      const param = {}
      param.latLng = {
        lat: latLng.lat,
        lng: latLng.lng
      }
      fun(param)
    })
  } else if (mapType === 'google') {
    window.google.maps.event.addListener(map, 'click', function(e) {
      const param = {}
      param.latLng = {
        lat: e.latLng.lat,
        lng: e.latLng.lng
      }
      fun(param)
    })
  }
}

export function addMarketClickListener(map, marker, fun) {
  if (mapType === 'baidu') {
    marker.addEventListener('click', function() {
      const param = {
        marker: marker
      }
      fun(param)
    })
  } else if (mapType === 'qq') {
    window.qq.maps.event.addListener(marker, 'click', function() {
      const param = {
        marker: marker
      }
      fun(param)
    })
  } else if (mapType === 'google') {
    marker.addListener('click', () => {
      const param = {
        marker: marker
      }
      fun(param)
    })
  }
}

export function clearAllLine(map) {
  if (mapType === 'baidu') {
    map.clearOverlays()
  } else if (mapType === 'qq') {
    if (map.ztn.polyline) {
      map.ztn.polyline.setMap(null)
    }
  } else if (mapType === 'google') {
    if (map.ztn.polyline) {
      map.ztn.polyline.setMap(null)
    }
  }
  map.ztn.polyline = null
}

export function clearAndMakeLine(map, points) {
  clearAllLine(map)
  return makeMapLine(map, points)
}

export function makeMapLine(map, points) {
  let polyline
  if (mapType === 'baidu') {
    const pList = []
    for (let i = 0; i < points.length; i++) {
      const point = points[i]
      pList.push(
        new window.BMap.Point(point.lng, point.lat)
      )
    }
    polyline = new window.BMap.Polygon(pList, { strokeColor: 'blue', strokeWeight: 2, strokeOpacity: 0.5 })
    map.addOverlay(polyline)
  } else if (mapType === 'qq') {
    const pList = []
    for (let i = 0; i < points.length; i++) {
      const point = points[i]
      const latLng = gcj_encrypt(point.lat, point.lng)
      pList.push(
        new window.qq.maps.LatLng(latLng.lat, latLng.lng)
      )
    }
    polyline = new window.qq.maps.Polyline({
      path: pList,
      map: map
    })
  } else if (mapType === 'google') {
    const pList = []
    for (let i = 0; i < points.length; i++) {
      const point = points[i]
      pList.push(
        new window.google.maps.LatLng(point.lat, point.lng)
      )
    }
    polyline = new window.google.maps.Polyline({
      path: pList,
      strokeColor: '#0000FF',
      strokeOpacity: 0.8,
      strokeWeight: 2
    })
    polyline.setMap(map)
  }
  map.ztn.polyline = polyline
  return polyline
}

export function makeMarkerCluster(map, markers) {
  let markerCluster
  if (mapType === 'baidu') {
    markerCluster = new window.BMapLib.MarkerClusterer(map, { markers: markers })
  } else if (mapType === 'qq') {
    markerCluster = new window.qq.maps.MarkerCluster({
      map: map,
      minimumClusterSize: 2, // 默认2
      markers: map.ztn.markerList,
      zoomOnClick: true, // 默认为true
      gridSize: 30, // 默认60
      averageCenter: true, // 默认false
      maxZoom: 18 // 默认18
    })
  } else if (mapType === 'google') {
    markerCluster = new window.markerClusterer.MarkerClusterer({
      markers,
      map
    })
  }
  return markerCluster
}

export function markerClusterAddMarker(map, markerCluster, marker) {
  if (mapType === 'baidu') {
    markerCluster.addMarker(marker)
  } else if (mapType === 'qq') {
    markerCluster.addMarker(marker)
  } else if (mapType === 'google') {
    markerCluster.addMarkers([marker])
  }
}
